package com.supermap.wzhy.module.context;

import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

/**
 * 映射服务器上下文，加载一次
 */
public class CodeMapServer {
    private Context ctx = null;

    public CodeMapServer() {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
        env.put(Context.PROVIDER_URL, "file:/");
        try {
            ctx = new InitialContext(env);
        } catch (NamingException e) {
            e.printStackTrace();
        }
        loadCodeMapInfo();
    }

    /**
     * 解析出作用表与目标表之间的映射关系
     */
    private void loadCodeMapInfo() {
        if (ctx != null) {
            //查询文件路径
            Properties props = this.propsFrom("path.properties");
            //保存映射信息
            Map<String, Hashtable<String, String>> codeMapInfos = new HashMap<>();
            String path = props.getProperty("path");
            List<String> filenames = Arrays.asList(StringUtils.commaDelimitedListToStringArray(path));
            for (String filename : filenames) {
                props = this.propsFrom(filename);
                Hashtable<String, String> codeMap = new Hashtable<>();
                Set keyValue = props.keySet();
                for (Iterator it = keyValue.iterator(); it.hasNext(); ) {
                    String actionCode = (String) it.next();
                    codeMap.put(actionCode, props.getProperty(actionCode));
                }
                String tblName = filename.replace(".properties", "");
                codeMapInfos.put(tblName, codeMap);
            }
            //构建rest stub
            CodeMapService codeMapService = new CodeMapService();
            codeMapService.setInfo(codeMapInfos);
            try {
                this.ctx.rebind("StubService", codeMapService);
            } catch (NamingException e) {
                e.printStackTrace();
            }
        }
    }

    public void close() throws NamingException {
        ctx.close();
    }

    public Context getContext() {
        return ctx;
    }

    /**
     * 解析properties文件
     *
     * @param path 文件路径
     * @return
     */
    private Properties propsFrom(String path) {
        InputStream in = getClass().getResourceAsStream(path);
        Properties props = new Properties();
        try {
            props.load(in);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return props;
    }
}
